let fs = require('fs')
let path = require('path')
let url = path.join(__dirname, './data.json')
//增
function addData(obj) {
  fs.readFile(url, 'utf8', (err, data) => {
    if (err) return console.log(err.message);
    let arr = JSON.parse(data)
    obj.id=arr[arr.length-1].id+1
    arr.push(obj)
    fs.writeFile(url, JSON.stringify(arr), err => {
      if (err) return console.log(err.message);
      console.log('添加成功');
    })
  })
}
// addData({
//     "author": "东方不败",
//     "bookname": "玉女心经",
//     "publisher": "人民出版社"
// })

//删
function delData(id) {
  fs.readFile(url, 'utf8', (err, data) => {
    if (err)  return console.log(err.message);
    let arr = JSON.parse(data)
    let newArr=[]
    arr.forEach(ele => {
      if (ele.id != id) {
        newArr.push(ele)
      }
    });
    fs.writeFile(url, JSON.stringify(newArr), err => {
      if (err) return console.log(err.message);
      console.log('删除成功');
    })
  })
}
// delData(5)

//改
function updateData(obj) {
  fs.readFile(url, 'utf8', (err, data) => {
    if (err) return console.log(err.message);
    let arr = JSON.parse(data)
    let index = arr.findIndex(ele => arr.id == obj.id)
    arr.splice(index, 1, obj)
    fs.writeFile(url, JSON.stringify(arr), err => {
      if (err) return console.log(err.message);
      console.log('修改成功');
    })
  })
}
// updateData({
//     "id":4,
//     "author": "东方不败",
//     "bookname": "玉女心经",
//     "publisher": "人民出版社"
// })

//查
function getData() {
  fs.readFile(url, 'utf8', (err, data) => {
    if (err) return console.log(err.message);
    console.log(data);
   })
}
getData()